package day20.pack1;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class Counter {

    private static final Unsafe unsafe;

    static {

        try {
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            unsafe = (Unsafe) field.get(null);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public int count;
    public int getCount() {
        return count;
    }

    public void increment() throws Exception {
        Field field = Counter.class.getDeclaredField("count");
        long memoryAddress = unsafe.objectFieldOffset(field);
        unsafe.getAndAddInt(this, memoryAddress, 1);
//        int oldValue;
//        int newValue;
//        do {
//            oldValue = count;
//            newValue = oldValue + 1;
//        } while(!unsafe.compareAndSwapInt(this, memoryAddress, oldValue, newValue));
    }


}
